package org.amphiprion.montrictracv4.fragment.dialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.amphiprion.montrictracv4.App;
import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.adapter.ExtensionListAdapter;
import org.amphiprion.montrictracv4.db.dao.LudothequeDao;
import org.amphiprion.montrictracv4.db.model.GameExtension;
import org.amphiprion.montrictracv4.db.model.GameExtensionList;
import org.amphiprion.montrictracv4.db.model.GameLanguage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;

public class ExtensionListFragment extends SherlockDialogFragment {
	private GameExtensionList extensionList;
	private View fragment;
	private ListView listView;
	private TextView lblCount;
	private ExtensionListAdapter adapter;
	private FragmentActivity context;
	private View viewLoading;
	private CheckBox chkOnlyNotOwned;

	public static ExtensionListFragment newInstance(GameExtensionList extensionList) {
		ExtensionListFragment frag = new ExtensionListFragment();
		frag.extensionList = extensionList;
		return frag;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		fragment = inflater.inflate(R.layout.fragment_extension_list, container);
		this.context = getActivity();
		this.viewLoading = fragment.findViewById(R.id.loading);
		LinearLayout llLang = ((LinearLayout) fragment.findViewById(R.id.llLanguages));
		this.listView = ((ListView) fragment.findViewById(R.id.lstGame));
		this.lblCount = ((TextView) fragment.findViewById(R.id.lblCount));

		this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View arg1, int row, long arg3) {
				try {
					GameExtension game = (GameExtension) adapter.getItemAtPosition(row);
					Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.trictrac.net/jeu-de-societe/" + game.id + "/infos"));
					startActivity(myIntent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(context, "No application can handle this request." + " Please install a webbrowser", Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		});

		chkOnlyNotOwned = (CheckBox) fragment.findViewById(R.id.chkOnlyNotOwned);
		chkOnlyNotOwned.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				initData();
			}
		});

		if (extensionList.languages.size() >= 1) {
			Collections.sort(extensionList.languages);
			extensionList.languages.get(0).checked = true;
		}
		if (extensionList.languages.size() >= 2) {
			for (final GameLanguage lang : extensionList.languages) {
				CheckBox chk = new CheckBox(context);
				chk.setChecked(lang.checked);
				llLang.addView(chk);
				if (lang.image != null && !"".equals(lang.image)) {
					ImageView img = new ImageView(context);
					LayoutParams params = new LayoutParams(App.dpiToPixels(context, 30), App.dpiToPixels(context, 30));

					img.setLayoutParams(params);
					App.setUrlDrawable(img, lang.image, this.getSherlockActivity().getSupportFragmentManager());
					llLang.addView(img);
				} else {
					chk.setText(lang.name);
				}

				chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						lang.checked = isChecked;
						initData();
					}
				});
			}
		}
		getDialog().setTitle(extensionList.game.name);
		initData();
		return fragment;
	}

	private void initData() {
		if (viewLoading != null) {
			viewLoading.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				List<GameExtension> list = new ArrayList<GameExtension>();

				boolean owned;
				for (GameExtension ext : extensionList.extensions) {
					boolean toAdd = false;
					String gameId = ext.id;
					owned = LudothequeDao.getInstance(context).isGameOwned(App.currentLudotheque.getId(), gameId);
					ext.owned = owned;
					toAdd = !owned || !chkOnlyNotOwned.isChecked();
					int index = extensionList.languages.indexOf(ext.lang);
					if (index != -1) {
						if (!extensionList.languages.get(index).checked) {
							toAdd = false;
						}
					}
					if (toAdd) {
						list.add(ext);
					}
				}
				onLoadDone(list);
			}
		}).start();
	}

	private void onLoadDone(final List<GameExtension> list) {
		((Activity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				lblCount.setText("" + list.size() + "/" + extensionList.extensions.size() + " ");
				adapter = new ExtensionListAdapter(context, ExtensionListFragment.this, R.layout.extension_list_item_row, list);
				listView.setAdapter(adapter);

				viewLoading.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
			}
		});
	}
}
